const { Service } = require('egg')

class HomeService extends Service{
    /**
     * 查询商品列表
     */
    async index(payload){
        const { ctx } = this;
        let { name = "" } = payload;
        const { Op } = this.ctx.model.Sequelize
        return await ctx.model.Goods.findAll({
            where: {
                name: {
                    [Op.like]: '%' + name + '%'
                }
            }
        })
    }

    /**
     * 商品修改
     */
    async update(payload){
        return await this.ctx.model.Goods.update(payload, {
            where: {
                id: payload.id
            }
        })
    }

    /**
     * 商品添加
     */
    async create(payload){
        return await this.ctx.model.Goods.create(payload)
    }

    /**
     * 商品删除
     */
    async delete(payload){
        return await this.ctx.model.Goods.destroy({
            where: {
                id: payload.goods_id
            }
        })
    }


    /**
     * 商品下报告列表
     */
    async goodsReport(payload){
        const { ctx } = this;
        const { goods_id, name = '' } = payload
        const { Op } = this.ctx.model.Sequelize
        return await ctx.model.Report.findAll({
            where: {
                goods_id,
                name: {
                    [Op.like]: '%' + name + '%'
                }
            },
            order: [['sortValue', 'DESC']]
        })
    }

    /**
     * 商品下溯源报告列表
     */
    async goodsTraceability(payload){
        const { ctx } = this;
        const { goods_id, name } = payload
        const { Op } = this.ctx.model.Sequelize
        return await ctx.model.Traceability.findAll({
            where: {
                goods_id,
                name: {
                    [Op.like]: '%' + name + '%'
                }
            },
            include: [
                { association: ctx.model.Traceability.hasMany(ctx.model.TraceabilityDetail, { foreignKey: 'trace_id' }) }
            ]
        })
    }
}


module.exports = HomeService